package com.itheima.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.mapper.ClazzMapper;
import com.itheima.mapper.EmpMapper;
import com.itheima.pojo.Clazz;
import com.itheima.pojo.Emp;
import com.itheima.pojo.PageResult;
import com.itheima.service.ClazzService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.time.LocalDate;
import java.util.List;

@Service
public class ClazzServiceImpl extends ServiceImpl<ClazzMapper, Clazz> implements ClazzService {

    @Autowired
    private EmpMapper empMapper;

    @Override
    public PageResult<Clazz> findPageClazz(String name,LocalDate begin, LocalDate end, int page, int pageSize) {

        LambdaQueryWrapper<Clazz> wrapper = Wrappers.lambdaQuery();
        wrapper.like(name!=null&&name!="",Clazz::getName,name)
                .between(begin!=null&&end!=null,Clazz::getEndDate,begin,end)
                .orderByDesc(Clazz::getUpdateTime);

        IPage<Clazz> page1 = this.page(new Page<>(page, pageSize), wrapper);

        List<Clazz> records = page1.getRecords();

        if(!CollectionUtils.isEmpty(records)){
            List<Integer> list = records.stream().map(clazz -> clazz.getMasterId()).distinct().toList();

            List<Emp> empList = empMapper.selectByIds(list);

            records.forEach(clazz ->
                    empList.stream().filter(emp -> emp.getId().equals(clazz.getMasterId()))
                            .findFirst()
                            .ifPresent(emp -> clazz.setMasterName(emp.getName()))
                    );
            for (Clazz clazz : records) {
                if(LocalDate.now().isBefore(clazz.getBeginDate())){
                    clazz.setStatus("未开班");
                } else if (LocalDate.now().isAfter(clazz.getEndDate())) {
                    clazz.setStatus("已结课");
                } else  {
                    clazz.setStatus("在读");
                }
            }
        }


        return new PageResult<>(page1.getTotal(),records);
    }
}
